const Scoket = require('socket.io');
const Redis = require('ioredis');
const adapter = require('socket.io-redis');
const config = require('./config.json');
const redis = new Redis(config.redis);
const sub = new Redis(config.redis);


sub.subscribe('rush');

module.exports = function SocketServer(server) {
  const io = Scoket(server, {...config.socket});
  let clientCount = 1;

  let userCount = 0;

  setInterval(() => {
    userCount = Object.keys(io.of('/').connected).length;
    io.emit('online', userCount);
  }, 60 * 1000)


  io.on('connect', (client) => {
    const uid = clientCount++;
    userCount += 1;
    io.emit('online', userCount);
    client.emit('uid', uid)

    client.on('client-ping', (data, ack) => {
      ack('pong');
    });

    client.on('uid', (data, ack) => {
      ack(uid);
    });

    client.on('rush', () => {
      redis.publish('rush', uid);
    });

    client.on('disconnect', () => {
      userCount = Math.max(0, userCount -1);
      io.emit('online', userCount);
    });

    client.on('watch', (watching, ack) => {

      sub.once('message', (channel, rushUid) => {
        if (channel === watching)
          ack(rushUid)
      });
    })

  })

  return io;
}